package org.sdp.pearproject.utils;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.codec.binary.Base64;

import java.nio.charset.StandardCharsets;
import java.util.Date;

public class JWTUtil {
    public static String getValue(String token, String key) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            String payload = jwt.getPayload();
            byte[] base64 = Base64.decodeBase64(payload.getBytes(StandardCharsets.UTF_8));
            JSONObject j = JSONObject.parseObject(new String(base64));
            return j.getJSONObject("data").getString(key);
        }catch(Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    public static Date getExp(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getExpiresAt();
        }catch(Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static String createToken(String code) {
        Date now = new Date();
        JSONObject data = new JSONObject();
        data.put("code", code);
        Date tsp = new Date();
        tsp.setTime(tsp.getTime() + 7L*24*60*60*1000);
        String token = JWT.create()
                .withExpiresAt(tsp)
                .withNotBefore(now)
                .withIssuedAt(now)
                .withIssuer("")
                .withAudience("")
                .withClaim("scopes", "access")
                .withClaim("exp", tsp)
                .withClaim("data", data)
                .sign(Algorithm.HMAC256("pearProject"));
        return token;
    }

}
